package ReqBean;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
public class RequestBean {
	public static final DateFormat TF_YMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 年月日时分秒
	public static final DateFormat TF_YMD=new SimpleDateFormat("yyyy-MM-dd");//年月日
	public static final DateFormat TF_YM=new SimpleDateFormat("yyyy-MM");//年月
	public static final DateFormat TF_YMDHM=new SimpleDateFormat("yyyy-MM-dd HH:mm");//年月日时分
	public static <T> T getBeanFromRequest(Class<T> beanClass, HttpServletRequest request)
			throws InstantiationException, IllegalAccessException {
		// 创建bean对象
		T bean = beanClass.newInstance();
		// 获取所有的方法
		Method[] mds = beanClass.getMethods();
		for (Method md : mds) {
			String mdName = md.getName();
			if (mdName.startsWith("set") && mdName.length() > 3 && md.getParameterCount() == 1) {
				String fname = mdName.replace("set", "").toLowerCase();
				String[] values = request.getParameterValues(fname);
				if (values == null) {
					continue;
				}
				Class<?> type = md.getParameterTypes()[0];
				try {
					if (type == String.class) {
						md.invoke(bean, values[0]);
					} else if (type == int.class || type == Integer.class) {
						md.invoke(bean, Integer.parseInt(values[0]));
					} else if (type == double.class || type == Double.class) {
						md.invoke(bean, Double.parseDouble(values[0]));
					} else if (type == float.class || type == Float.class) {
						md.invoke(bean, Float.parseFloat(values[0]));
					} else if (type == long.class || type == Long.class) {
						md.invoke(bean, Long.parseLong(values[0]));
					} else if (type.equals(java.util.Date.class)) {
						try {
							md.invoke(bean,TF_YMDHMS.parse(values[0]));
						}  catch (ParseException e) {
							try {
								md.invoke(bean,TF_YMD.parse(values[0]));
							}catch (ParseException e1) {
								try {
									md.invoke(bean,TF_YM.parse(values[0]));
								} catch (ParseException e2) {
									try {
										md.invoke(bean,TF_YMDHM.parse(values[0]));
									} catch (Exception e3) {
										e3.printStackTrace();
									}
								}
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return bean;
	}
}
